<?php


namespace Frontend\Controllers;

use Phalcon\Logger;

use Models\AlipayAreply;
use Models\AlipayImg;
use Models\AlipayImgmulti;
use Models\AlipayKeyword;
use Models\AlipayText;


class AlipayController extends BaseController
{
    public function beforeExecuteRoute($dispatcher)
    {
        parent::beforeExecuteRoute($dispatcher);
        //加载alipay sdk
        include $this->config->application->libDir . "alipay/AopSdk.php";
    }

    public function indexAction($appid)
    {

        $config = $this->config;
        $appId = $appid;
        //根据token获取商户appid
//       $appId = '2014121300019751';

        $service = $this->request->getPost('service');

        $client = new \AopClient();
        $client->rsaPrivateKeyFilePath = $config->rsaPrivateKeyPath;
        $client->appId = $appId;


        if (!$client->rsaCheckV2($_POST, $config->alipayFuwuRsaPublicKeyPath)) {
            echo '非法请求！';
            exit;
        }


        if ($service == "alipay.service.check") {
            $biz_content = '<biz_content>' . $config->alipayFuwuRsaPublicKey . '</biz_content><success>true</success>';
            $sign = $client->encryptAndSign($biz_content, '', '', 'GBK', false, true);
            echo $sign;
            exit;
        }
        if ($service == "alipay.mobile.public.message.notify") {

            $biz_content = $this->request->getPost('biz_content');
            $xml = $this->parseXML(iconv('GBK', 'UTF-8', $biz_content));
            $AppId = (string)$xml->AppId;
            $MsgType = (string)$xml->MsgType;
            $FromUserId = (string)$xml->FromUserId;
            if ($MsgType == "text") {
                $keyword = $xml->Text->Content;
                $type = AlipayKeyword::findFirst("keyword='" . $keyword . "'and appid='" . $appid . "'");
                if ($type->module == "Img") {
                    $img = AlipayImg::findFirst("keyword='" . $keyword . "'and appid='" . $appid . "'");
                    $url = strpos($img->url, "app.1yizu.com");
                    if ($img->url == "") {
                        $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                    }
                    if ($url) {
                        $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                    }
//                    $this->logger->debug($img->url);
                    $news = array(
                        0 => array("actionName" => "立即查看",
                            "desc" => $img->intro,
                            "imageUrl" => $config->host . $img->pic,
                            "title" => $img->title,
                            "url" => $img->url
                        )
                    );
                    $r_biz = $this->buildImg($news, $FromUserId);
                    $req = new \AlipayMobilePublicMessageCustomSendRequest();
                    $req->setBizContent($r_biz);
                    $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                    return;
                } elseif ($type->module == "Text") {
                    $text = AlipayText::findFirst("keyword='" . $keyword . "'and appid='" . $appid . "'");
                    $r_biz = $this->buildText($text->text, $FromUserId);
                    $req = new \AlipayMobilePublicMessageCustomSendRequest();
                    $req->setBizContent($r_biz);
                    $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                    return;
                } elseif ($type->module == "Multi") {
                    $imgs = AlipayImgmulti::findFirst("keyword='" . $keyword . "'and appid='" . $appid . "'");
                    $id = explode(',', $imgs->imgs);
                    foreach ($id as $k => $v) {
                        $img = AlipayImg::findFirstByid($v);
                        $url = strpos($img->url, "app.1yizu.com");
                        if ($img->url == "") {
                            $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                        }
                        if ($url) {
                            $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                        }
                        $news[$k] = array("actionName" => "立即查看",
                            "desc" => $img->intro,
                            "imageUrl" => $config->host . $img->pic,
                            "title" => $img->title,
                            "url" => $img->url
                        );
                    }
                    $r_biz = $this->buildImg($news, $FromUserId);
                    $req = new \AlipayMobilePublicMessageCustomSendRequest();
                    $req->setBizContent($r_biz);
                    $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                    return;
                }
            }
            if ($MsgType == 'image') {
                $r_biz = $this->buildText("图片", $FromUserId);
                $req = new \AlipayMobilePublicMessageCustomSendRequest();
                $req->setBizContent($r_biz);
                $resp = $client->execute($req);//TODO 可以根据返回情况记录日志
                return;
            }
            if ($MsgType == "event") {
                $EventType = (string)$xml->EventType;
                switch ($EventType) {
                    case "follow": //关注事件
                        $text = AlipayAreply::findFirst("appid='" . $appid . "'");
                        if ($text->check == "on") {
                            $type = AlipayKeyword::findFirst("keyword='" . $text->keyword . "'and appid='" . $appid . "'");
                            if ($type->module == "Img") {
                                $img = AlipayImg::findFirst("id='" . $type->pid . "'");
                                $url = strpos($img->url, "app.1yizu.com");
                                if ($img->url == "") {
                                    $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                                }
                                if ($url) {
                                    $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                                }
                                $news = array(
                                    0 => array("actionName" => "立即查看",
                                        "desc" => $img->intro,
                                        "imageUrl" => $config->host . $img->pic,
                                        "title" => $img->title,
                                        "url" => $img->url
                                    )
                                );
                                $r_biz = $this->buildImg($news, $FromUserId);
                                $req = new \AlipayMobilePublicMessageCustomSendRequest();
                                $req->setBizContent($r_biz);
                                $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                                return;
                            } elseif ($type->module == "Text") {
                                $text = AlipayText::findFirst("id='" . $type->pid . "'");
                                $r_biz = $this->buildText($text->text, $FromUserId);
                                $req = new \AlipayMobilePublicMessageCustomSendRequest();
                                $req->setBizContent($r_biz);
                                $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                                return;
                            } elseif ($type->module == "Multi") {
                                $imgs = AlipayImgmulti::findFirst("keyword='" . $text->keyword . "'and appid='" . $appid . "'");
                                $id = explode(',', $imgs->imgs);
                                foreach ($id as $k => $v) {
                                    $img = AlipayImg::findFirstByid($v);
                                    $url = strpos($img->url, "app.1yizu.com");
                                    if ($img->url == "") {
                                        $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                                    }
                                    if ($url) {
                                        $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                                    }
                                    $news[$k] = array("actionName" => "立即查看",
                                        "desc" => $img->intro,
                                        "imageUrl" => $config->host . $img->pic,
                                        "title" => $img->title,
                                        "url" => $img->url
                                    );
                                }
                                $r_biz = $this->buildImg($news, $FromUserId);
                                $req = new \AlipayMobilePublicMessageCustomSendRequest();
                                $req->setBizContent($r_biz);
                                $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                                return;
                            }
                        } else {
                            $r_biz = $this->buildText($text->content, $FromUserId);
                            $req = new \AlipayMobilePublicMessageCustomSendRequest();
                            $req->setBizContent($r_biz);
                            $resp = $client->execute($req);//TODO 可以根据返回情况记录日志
                            return;
                        }
                        break;
                    case "unfollow": //取消关注
                        break;
                    case "enter": //进入服务窗
                        break;
                    case "click": //点击事件
                        $ActionParam = (string)$xml->ActionParam;
                        $type = AlipayKeyword::findFirst("keyword='" .$ActionParam. "'and appid='" . $appid . "'");
                        if ($type->module == "Img") {
                            $img = AlipayImg::findFirst("id='" . $type->pid . "'");
                            $url = strpos($img->url, "app.1yizu.com");
                            if ($img->url == "") {
                                $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                            }
                            if ($url) {
                                $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                            }
                            $news = array(
                                0 => array("actionName" => "立即查看",
                                    "desc" => $img->intro,
                                    "imageUrl" => $config->host . $img->pic,
                                    "title" => $img->title,
                                    "url" => $img->url
                                )
                            );
                            $r_biz = $this->buildImg($news, $FromUserId);
                            $req = new \AlipayMobilePublicMessageCustomSendRequest();
                            $req->setBizContent($r_biz);
                            $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                            return;
                        } elseif ($type->module == "Text") {
                            $text = AlipayText::findFirst("id='" . $type->pid . "'");
                            $r_biz = $this->buildText($text->text, $FromUserId);
                            $req = new \AlipayMobilePublicMessageCustomSendRequest();
                            $req->setBizContent($r_biz);
                            $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                            return;
                        } elseif ($type->module == "Multi") {
                            $imgs = AlipayImgmulti::findFirst("keyword='" . $ActionParam . "'and appid='" . $appid . "'");
                            $id = explode(',', $imgs->imgs);
                            foreach ($id as $k => $v) {
                                $img = AlipayImg::findFirstByid($v);
                                $url = strpos($img->url, "app.1yizu.com");
                                if ($img->url == "") {
                                    $img->url = $config->host . '/frontend/alipay/imgtext/' . $img->id . '?appid=' . $appid;
                                }
                                if ($url) {
                                    $img->url = $img->url . "?appid=".$AppId."&openid=".$FromUserId;
                                }
                                $news[$k] = array("actionName" => "立即查看",
                                    "desc" => $img->intro,
                                    "imageUrl" => $config->host . $img->pic,
                                    "title" => $img->title,
                                    "url" => $img->url
                                );
                            }
                            $r_biz = $this->buildImg($news, $FromUserId);
                            $req = new \AlipayMobilePublicMessageCustomSendRequest();
                            $req->setBizContent($r_biz);
                            $resp = $client->execute($req); //TODO 可以根据返回情况记录日志
                            return;
                        }
                        return;
                        break;
                    default :
                        break;
                }
                return;
            }
        }


    }


    private function buildText($content, $toUserId, $createTime = null)
    {
        $obj = array();
        $obj['toUserId'] = $toUserId;
        $obj['msgType'] = 'text';
        $obj['createTime'] = $createTime ? $createTime : time();
        $obj['text'] = array('content' => $content);
        return json_encode($obj);
    }

    private function buildImg($articles, $toUserId, $createTime = null)
    {
        $obj = array();
        $obj['toUserId'] = $toUserId;
        $obj['msgType'] = 'image-text';
        $obj['createTime'] = $createTime ? $createTime : time();
        $obj['articles'] = $articles;
        return json_encode($obj);
    }

    private function parseXML($biz_content)
    {
        $xml = simplexml_load_string($biz_content, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $xml;
    }

    public function imgtextAction($id)
    {
        //TODO 根据token做安全检查
//        $token = $this->request->get('token');
        $it = AlipayImg::findFirst($id);
        $this->view->it = $it;
    }
}